package org.custom.spring.boot.datasource.utils;

import org.custom.spring.boot.datasource.constant.HttpConstant;
import org.custom.spring.boot.datasource.entity.RestTemplatePropertity;
import org.custom.spring.boot.datasource.exception.TipException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;

import java.net.URI;
import java.util.Optional;

import static org.custom.spring.boot.datasource.constant.JettExceptionConstant.HTTP_METHOD_ERROR;

/**
 * RestTemplate相关工具类
 *
 * @author 李坤
 * @date 2022/3/31 17:30
 */
public abstract class RestTemplateUtil {

    /**
     * 根据 RestTemplate 请求信息 生成 RequestEntity 对象
     *
     * @param templatePropertity RestTemplate 请求信息
     *
     * @return RequestEntity 对象
     */
    public static RequestEntity generateRequestEntity(RestTemplatePropertity templatePropertity) {
        // 解析请求路径
        URI uri = URI.create(templatePropertity.getUrl());
        // 生成并添加头信息
        HttpHeaders httpHeaders = templatePropertity.obtainHttpHeaders();
        // 生成 HttpMethod 对象
        HttpMethod httpMethod = RestTemplateUtil.getHttpMethod(templatePropertity.getHttpMethod());

        // 生成 RequestEntity 对象
        return new RequestEntity<>(templatePropertity.getParams(), httpHeaders, httpMethod, uri);
    }

    /**
     * 根据 httpMethod 获取 HttpMethod 枚举对象
     *
     * @param httpMethodStr 字符串类型请求方式
     *
     * @return HTTP请求方式
     */
    public static HttpMethod getHttpMethod(String httpMethodStr) {
        HttpMethod httpMethod;

        // 根据用户传递的请求方式匹配 HttpMethod
        switch (httpMethodStr.toUpperCase()) {
            case HttpConstant.RequestType.GET:
                httpMethod = HttpMethod.GET;
                break;
            case HttpConstant.RequestType.PUT:
                httpMethod = HttpMethod.PUT;
                break;
            case HttpConstant.RequestType.HEAD:
                httpMethod = HttpMethod.HEAD;
                break;
            case HttpConstant.RequestType.POST:
                httpMethod = HttpMethod.POST;
                break;
            case HttpConstant.RequestType.PATCH:
                httpMethod = HttpMethod.PATCH;
                break;
            case HttpConstant.RequestType.TRACE:
                httpMethod = HttpMethod.TRACE;
                break;
            case HttpConstant.RequestType.DELETE:
                httpMethod = HttpMethod.DELETE;
                break;
            case HttpConstant.RequestType.OPTIONS:
                httpMethod = HttpMethod.OPTIONS;
                break;
            default:
                httpMethod = null;
                break;
        }
        return Optional.ofNullable(httpMethod).orElseThrow(() -> new TipException(String.format(HTTP_METHOD_ERROR, httpMethodStr)));
    }

}
